package com.sx.gongzhong.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.MyFragmentPagerAdapter;
import com.sx.gongzhong.fragment.ExposureFragment;
import com.sx.gongzhong.fragment.MainPagerFragment;
import com.sx.gongzhong.fragment.MessageFragment;
import com.sx.gongzhong.fragment.MyFragment;
import com.sx.gongzhong.model.VersionBean;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.VersionPest;
import com.sx.gongzhong.port.PermissionsResultListener;
import com.sx.gongzhong.utils.AppConstants;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVersionView;
import com.sx.gongzhong.widget.BaseDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, IVersionView {

    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.rbt_MainPager)
    RadioButton rbt_MainPager;
    @BindView(R.id.rbt_TipOff)
    RadioButton rbt_TipOff;
    @BindView(R.id.rbt_Message)
    RadioButton rbt_Message;
    @BindView(R.id.rbt_My)
    RadioButton rbt_My;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tvVersion)
    TextView tvVersion;
    @BindView(R.id.img_Add)
    ImageView img_Add;
    private int current = 0 ;

    private List<Fragment> fragments = new ArrayList<>();

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setGoneTitle();
        setViews();
        new VersionPest(this).getVersion();
        performRequestPermissions(AppConstants.FORCE_REQUIRE_PERMISSIONS, 100, new PermissionsResultListener() {
            @Override
            public void onPermissionGranted() {
            }
            @Override
            public void onPermissionDenied() {
            }
        });
    }

    private void setViews() {
        fragments.add(new MainPagerFragment());
        fragments.add(new ExposureFragment());
        fragments.add(new MessageFragment());
        fragments.add(new MyFragment());
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),
                fragments, null);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);
        radioGroup.setOnCheckedChangeListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        current = 0;
                        rbt_MainPager.setChecked(true);
                        break;
                    case 1:
                        current = 1;
                        rbt_TipOff.setChecked(true);
                        break;
                    case 2:
                        rbt_Message.setChecked(true);
                        break;
                    case 3:
                        current = 3;
                        rbt_My.setChecked(true);
                        break;
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }

    @OnClick({R.id.img_Add})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.img_Add:
                if (isLogin()){
                    startActivity(new Intent(MainActivity.this,ExposureAddActivity.class));
                }
                break;
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId){
            case R.id.rbt_MainPager:
                current = 0;
                viewPager.setCurrentItem(0);
                break;
            case R.id.rbt_TipOff:
                current = 1;
                viewPager.setCurrentItem(1);
                break;
            case R.id.rbt_Message:
                if (isLogin()) {
                    viewPager.setCurrentItem(2);
                }else {
                    switch (current){
                        case 0:
                            rbt_MainPager.setChecked(true);
                            break;
                        case 1:
                            rbt_TipOff.setChecked(true);
                            break;
                        case 3:
                            rbt_My.setChecked(true);
                            break;
                    }
                }
                break;
            case R.id.rbt_My:
                current = 3;
                viewPager.setCurrentItem(3);
                break;

        }
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showToast(MainActivity.this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                MyApplication.instance.finishAllActivity();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showError(String message) {

    }

    @Override
    public void getVersion(VersionBean versionBean) {
        if (versionBean!=null){
            if (versionBean.getVersionNum() > BaseUtil.getVersionCode(this)){
//                tvVersion.setVisibility(View.GONE);
//                UpdateVersionUtil.showDialog(MainActivity.this,findViewById(R.id.rl),versionBean);
                update(versionBean);
            }else {
//                ToastUtils.showToast(MainActivity.this,"当前已是最新版");
            }
        }
    }

    public void update(final VersionBean bean){
        DownloadBuilder builder =  AllenVersionChecker
                .getInstance()
                .downloadOnly(crateUIData(bean));
        builder.setForceRedownload(true); //默认false 如果本地有安装包缓存也会重新下载apk
        builder.setShowDownloadingDialog(true);//  默认true//是否显示下载对话框
        builder.setShowNotification(true);  //默认true 是否显示通知栏
        builder.setNotificationBuilder(
                NotificationBuilder.create()
                        .setRingtone(false)
                        .setIcon(R.mipmap.app_logo)
                        .setTicker("custom_ticker")
                        .setContentTitle("平安得令哈")
                        .setContentText("下载中")
        );
        builder.setCustomVersionDialogListener(new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData versionBundle) {
                BaseDialog baseDialog = new BaseDialog(context, R.style.BaseDialog, R.layout.version_update_dialog);
                TextView textView = baseDialog.findViewById(R.id.tv_Content);
                textView.setText(versionBundle.getContent());
                Button button = baseDialog.findViewById(R.id.versionchecklib_version_dialog_cancel);
                if (bean.isUpgrade()){
                    button.setVisibility(View.GONE);
                }else {
                    button.setVisibility(View.VISIBLE);
                }
                return baseDialog;
            }
        });
        if (bean.isUpgrade()){
            builder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                    forceUpdate();
                }
            });
        }
//        builder.setSilentDownload(true);// 默认false
        builder.setShowDownloadFailDialog(false);// 默认true
        builder.excuteMission(this);

    }

    /**
     * 强制更新操作
     * 通常关闭整个activity所有界面，这里方便测试直接关闭当前activity
     */
    private void forceUpdate() {
        ToastUtils.showToast(this,"请更新应用才可使用");
        MyApplication.context.finishAllActivity();
        finish();
    }

    /**
     * @return
     * @important 使用请求版本功能，可以在这里设置downloadUrl
     * 这里可以构造UI需要显示的数据
     * UIData 内部是一个Bundle
     */
    private UIData crateUIData(VersionBean bean) {
        UIData uiData = UIData.create();
        uiData.setTitle("版本更新");
        uiData.setDownloadUrl(ServiceFactory.getUrl( File.separator + bean.getDownloadUrl()));
        uiData.setContent(bean.getUpdateContent());
        return uiData;
    }
}
